//
//  UULoginManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 13/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UULoginManager.h"
#import <UUFoundation/DKDataManager.h>
#import <UUFoundation/UUPersistenceManager.h>
#import "UULoginRequestModel.h"
#import "UULogoutRequestModel.h"
#import "UULoginVerifyCodeRequestModel.h"

@interface UULoginManager ()

@property (nonatomic, strong) DKDataManager *loginRequest;

@end

@implementation UULoginManager

- (void)invalidate {
    [super invalidate];
    
    self.currentUser = nil;
}

- (BOOL)isLogin {
    return self.currentUser.token != nil && self.currentUser.userId != nil;
}

- (void)loginWithMobile:(NSString *)mobile
             verifyCode:(NSString *)verifyCode
          completeBlock:(void (^)(NSError *))completeBlock {
    [self.loginRequest cancelRequest];
    
    UULoginRequestModel *requestModel = [UULoginRequestModel new];
    requestModel.mobile = mobile;
    requestModel.verifyCode = verifyCode;
    [self.loginRequest requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) { // 登录成功，保存 token
            UULoginResponseModel *loginResponseModel = (UULoginResponseModel *)responseModel;
            [self loginWithUserId:loginResponseModel.userId token:loginResponseModel.token];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)loginWithUserId:(id)userId token:(NSString *)token {
    DKAssert(token != nil);
    DKAssert(userId != nil);
    
    self.currentUser.token = token;
#ifdef ENABLE_DEMO_ACCOUNT
    self.currentUser.userId = @1;
#else
    self.currentUser.userId = userId;
#endif
    
    [self saveCurrentUser:self.currentUser];
}

- (void)logout {
    self.currentUser.userId = nil;
    [[DKDataManager new] requestWithRequestModel:[UULogoutRequestModel new] completedBlock:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.currentUser.token = nil;
        [self saveCurrentUser:self.currentUser];
    });
}

- (void)sendVerifyCodeWithMobile:(NSString *)mobile completeBlock:(void (^)(NSError *))completeBlock {
    UULoginVerifyCodeRequestModel *requestModel = [UULoginVerifyCodeRequestModel new];
    requestModel.mobile = mobile;
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

#pragma mark - Private methods

- (void)saveCurrentUser:(UUCurrentUser *)currentUser {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:currentUser];
    [GetPersistenceManager().commonDefaults setObject:data forKey:@"CurrentUser"];
}

- (UUCurrentUser *)loadCurrentUser {
    NSData *data = [GetPersistenceManager().commonDefaults objectForKey:@"CurrentUser"];
    if (data) {
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    } else {
        return nil;
    }
}

#pragma mark - Getter, Setter methods

- (UUCurrentUser *)currentUser {
    if (_currentUser == nil) {
        _currentUser = [self loadCurrentUser];
        
        if (_currentUser == nil) {
            _currentUser = [UUCurrentUser new];
        }
    }
    
    return _currentUser;
}

- (DKDataManager *)loginRequest {
    if (_loginRequest == nil) {
        _loginRequest = [DKDataManager new];
    }
    
    return _loginRequest;
}

@end
